﻿using System;
using System.Net.Mime;
using System.Xml.Serialization;

namespace ICalendar.CalendarProperties
{
    /// <summary>
    /// The property provides the capability to associate a document object with a calendar component.
    /// </summary>
    [Serializable]
    [XmlRoot("attach")]  
    public class Attachment : CalendarPropertyBase<string>
    {
        public ContentType ContentType { get; set; }
        public ValueType ValueType { get; private set; }

        public Attachment(Uri value)
            : this(value, null)
        {
            
        }
        public Attachment(byte[] value)
            : this(value, null)
        {

        }

        public Attachment(byte[] value, ContentType contentType)
        {
            this.ContentType = contentType;
            this.Value = Convert.ToBase64String(value);
            this.ValueType = ValueType.Binary;
        }
        
        public Attachment(Uri value, ContentType contentType)
        {
            this.ContentType = contentType;
            this.Value = value.ToString();
            this.ValueType = ValueType.URI;
        }

        protected override void SetParametersFromXParameters(XParameterCollection xparams)
        {           
            var fmtype = xparams.GetValue("FMTTYPE");
            ContentType = string.IsNullOrEmpty(fmtype) ? null : new ContentType(fmtype);
            var valueName = xparams.GetValue("VALUE");
            this.ValueType = !string.IsNullOrEmpty(valueName) ? ValueType.FromName(valueName) : ValueType.URI;
        }

        protected override XParameterCollection GetXParametersFromParameters()
        {
            var xparams = new XParameterCollection
                              {
                                  {"FMTTYPE", this.ContentType.ToString()}
                              };

            if (this.ValueType == ValueType.Binary)
            {
                xparams.Add("VALUE", ValueType.Binary.GetName());
                xparams.Add("ENCODING", "BASE64");
            }

            return xparams;
        }

        protected override string[] GetXReservedParametersNames()
        {
            return new[] { "VALUE", "ENCODING", "FMTTYPE" };
        }

        protected override void SetValue(string value)
        {
            this.Value = value;
        }

        protected override string GetValue()
        {
            return this.Value;
        }
    }
}